package com.leather.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.leather.admin.entity.Permission;
import com.leather.admin.service.PermissionService;
import com.leather.admin.vo.PermissionVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RequestMapping("/admin/permission")
@Controller
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @RequiresPermissions("admin:user:index")
    @GetMapping("/index")
    public String index() {
        return "permission/index";
    }

    @RequiresPermissions("admin:user:index")
    @ResponseBody
    @GetMapping("list")
    public Object getPermission(
            @RequestParam(required = false, defaultValue = "0") int offset,
            @RequestParam(required = false, defaultValue = "10") int limit,
            @RequestParam(required = false, defaultValue = "asc") String order,
            @RequestParam(required = false, defaultValue = "") String search

    ) {
        Map<String, Object> map = Maps.newHashMap();
        Page<Permission> page = new Page<>(offset / 10 + 1, limit);
        IPage<Permission> permissions = permissionService.getAllPermission(page, order, search.trim());
        map.put("total", permissions.getTotal());
        map.put("rows", permissions.getRecords());
        return map;
    }

    @RequiresPermissions("admin:user:create")
    @GetMapping("/create")
    public String create() {
        return "permission/create";
    }

    @ResponseBody
    @PostMapping("/create")
    @RequiresPermissions("admin:user:create")
    public Object create(PermissionVo permissionVo) {
        return permissionService.addPermission(permissionVo);
    }

    @RequiresPermissions("admin:user:create")
    @ResponseBody
    @GetMapping("/parentlist")
    public Object getParent() {
        Map<String, Object> map = Maps.newHashMap();
        map.put("rows", permissionService.getParent());
        return map;
    }

    @RequiresPermissions("admin:user:create")
    @GetMapping("/update/{id}")
    public String update(@PathVariable("id") int id, Model model) {
        Permission permisson = permissionService.getById(id);
        model.addAttribute("permission", permisson);
        return "permission/update";
    }

    @RequiresPermissions("admin:user:create")
    @PostMapping("/update")
    @ResponseBody
    public Object postUpdate(PermissionVo permissionVo) {
        return permissionService.updatePermission(permissionVo);
    }

}
